﻿#include "servermonitorcenter.h"
#include <QDebug>
#include <qcpuinfoprovider.h>
#include <qdiskinfoprovider.h>
#include <qdiskmonitor.h>
#include <qmemoryinfoprovider.h>
#include <qnetworkadapterinfoprovider.h>

QMutex ServerMonitorCenter::mutex;
ServerMonitorCenter *ServerMonitorCenter::instance = nullptr;

ServerMonitorCenter *ServerMonitorCenter::getInstance()
{
    if (instance == nullptr)
    {
        QMutexLocker locker(&mutex);
        if (instance == nullptr)
        {
            instance = new ServerMonitorCenter();
        }
    }
    return instance;
}

void ServerMonitorCenter::deleteInstance()
{
    if (instance != nullptr)
    {
        delete instance;
        instance = nullptr;
    }
}

void ServerMonitorCenter::getServerInfo(ServerInfo &info)
{
    info = serverInfo;
}

void ServerMonitorCenter::getCpuInfoList(QList<CpuInfo> &list)
{
    list = cpuInfoList;
}

void ServerMonitorCenter::getMemoryInfoList(QList<MemoryInfo> &list)
{
    list = memoryInfoList;
}

void ServerMonitorCenter::getDiskInfoList(QList<DiskInfo> &list)
{
    QMutexLocker locker(&diskInfoListMutex);
    list = diskInfoList;
}

void ServerMonitorCenter::getCpuUseList(QList<CpuUse> &list)
{
    QMutexLocker locker(&cpuUseListMutex);
    list = cpuUseList;
}

void ServerMonitorCenter::getMemoryUseList(QList<MemoryUse> &list)
{
    QMutexLocker locker(&memoryUseListMutex);
    list = memoryUseList;
}

void ServerMonitorCenter::getVirtualMemoryUseList(QList<MemoryUse> &list)
{
    QMutexLocker locker(&virtualMemoryUseListMutex);
    list = virtualMemoryUseList;
}

void ServerMonitorCenter::getDiskUseList(QList<DiskUse> &list)
{
    QMutexLocker locker(&diskUseListMutex);
    list = diskUseList;
}

void ServerMonitorCenter::getNetworkInfoList(QList<NetworkInfo> &list)
{
    QMutexLocker locker(&networkInfoListMutex);
    list = networkInfoList;
}

void ServerMonitorCenter::getNetworkUseList(QList<NetworkUse> &list)
{
    QMutexLocker locker(&networkUseListMutex);
    list = networkUseList;
}

ServerMonitorCenter::ServerMonitorCenter(QObject *parent)
    : QThread(parent)
{
    qDebug() << __FUNCTION__;
    moveToThread(this);
    tempCountSize = 60;

    serverInfo.setKernelType(QSysInfo::kernelType());
    serverInfo.setCurrentCpuArchitecture(QSysInfo::currentCpuArchitecture());
    serverInfo.setKernelType(QSysInfo::kernelType());
    serverInfo.setKernelVersion(QSysInfo::kernelVersion());
    serverInfo.setProductType(QSysInfo::productType());
    serverInfo.setProductVersion(QSysInfo::productVersion());
    serverInfo.setPrettyProductName(QSysInfo::prettyProductName());
    serverInfo.setMachineHostName(QSysInfo::machineHostName());
    serverInfo.setMachineUniqueId(QSysInfo::bootUniqueId());

    //获取cpu信息
    QCpuInfoProvider cpu_provider;
    auto detailses = cpu_provider.getAllCpusDetails();
    foreach (auto &details, detailses)
    {
        CpuInfo cpuInfo;
        cpuInfo.setModel(details.model);
        cpuInfo.setVendor(details.vendor);
        cpuInfo.setArchitecture(details.architecture);
        cpuInfo.setPhysicalCores(details.physicalCores);
        cpuInfo.setLogicalCores(details.logicalCores);
        cpuInfo.setCacheSize(details.cacheSize);
        cpuInfo.setMaxFrequency(details.maxFrequency);
        cpuInfo.setMinFrequency(details.minFrequency);
        cpuInfoList.append(cpuInfo);
    }
    //获取内存信息
    QMemoryInfoProvider mem_provider;
    auto memories = mem_provider.getAllMemoryDetails();
    foreach (auto &memory, memories)
    {
        MemoryInfo memoryInfo;
        memoryInfo.setManufacturer(memory.manufacturer);
        memoryInfo.setPartNumber(memory.partNumber);
        memoryInfo.setSerialNumber(memory.serialNumber);
        memoryInfo.setMemoryType(memory.memoryType);
        memoryInfo.setSpeed(memory.speed);
        memoryInfo.setCapacity(memory.capacity.toULongLong());
        memoryInfoList.append(memoryInfo);
    }
    //获取网卡信息
    QNetworkAdapterInfoProvider provider;
    QVector<QNetworkAdapterInfoProvider::NetworkAdapterDetails> adapters = provider.getNetworkAdapters();

    for (const auto &adapter : adapters)
    {
        NetworkInfo netWork;
        netWork.setName(adapter.name);
        netWork.setIndex(adapter.index);
        netWork.setDescription(adapter.description);
        netWork.setMacAddress(adapter.macAddress);
        netWork.setType(adapter.type);
        netWork.setMtu(adapter.mtu);
        netWork.setSpeed(adapter.speed);
        netWork.setAdminUp(adapter.isAdminUp);
        netWork.setOperationalStatus(adapter.operationalStatus);
        networkInfoList.append(netWork);
    }
    start();
}

ServerMonitorCenter::~ServerMonitorCenter()
{
    quit();
    wait();
    qDebug() << __FUNCTION__;
}

void ServerMonitorCenter::slot_updateInfo()
{
    // 获取cpu使用率信息
    CpuUse cpuUse;
    //    cpuUse.setSelfUsageRate(cpuMonitor.processUsage(0));
    cpuUse.setUsageRate(cpuMonitor.systemUsage());
    cpuUse.setComputeTime(QDateTime::currentDateTime());

    cpuUseListMutex.lock();
    cpuUseList.push_back(cpuUse);
    while (cpuUseList.size() > tempCountSize)
    {
        cpuUseList.pop_front();
    }
    cpuUseListMutex.unlock();

    // 获取内存使用率信息
    MemoryUse memoryUse;
    uint64_t selfMemUse, memUse, memTotal;
    //物理内存
    memoryMonitor.getProcessPhysicalMemory(0, selfMemUse);
    memoryMonitor.getSystemPhysicalMemory(memUse, memTotal);
    memoryUse.setSelfUsageSize(selfMemUse);
    memoryUse.setUsageSize(memUse);
    memoryUse.setTotalsize(memTotal);
    memoryUse.setComputeTime(QDateTime::currentDateTime());

    memoryUseListMutex.lock();
    memoryUseList.push_back(memoryUse);
    while (memoryUseList.size() > tempCountSize)
    {
        memoryUseList.pop_front();
    }
    memoryUseListMutex.unlock();

    //虚拟内存
    memoryMonitor.getProcessVirtualMemory(0, selfMemUse);
    memoryMonitor.getSystemVirtualMemory(memUse, memTotal);
    memoryUse.setSelfUsageSize(selfMemUse);
    memoryUse.setUsageSize(memUse);
    memoryUse.setTotalsize(memTotal);
    memoryUse.setComputeTime(QDateTime::currentDateTime());

    virtualMemoryUseListMutex.lock();
    virtualMemoryUseList.push_back(memoryUse);
    while (virtualMemoryUseList.size() > tempCountSize)
    {
        virtualMemoryUseList.pop_front();
    }
    virtualMemoryUseListMutex.unlock();

    //获取磁盘信息
    QDiskInfoProvider disk_provider;
    auto disks = disk_provider.getAllDisksDetails();

    diskInfoListMutex.lock();
    diskInfoList.clear();
    foreach (auto &disk, disks)
    {
        DiskInfo diskInfo;
        diskInfo.setDevice(disk.device);
        diskInfo.setModel(disk.model);
        diskInfo.setSerialNumber(disk.serialNumber);
        diskInfo.setSize(disk.size.toULongLong());
        diskInfo.setInterfaceType(disk.interfaceType);
        diskInfo.setPartitionCount(disk.partitionCount);
        diskInfoList.append(diskInfo);
    }
    diskInfoListMutex.unlock();

    //获取磁盘使用情况
    QDiskMonitor diskMonitor;
    QList<DiskUseInfo> diskUseInfos = diskMonitor.getAllDiskUseInfo();

    diskUseListMutex.lock();
    diskUseList.clear();
    uint64_t diskAllUsageSize = 0;
    uint64_t diskAllTotalSize = 0;
    for (const DiskUseInfo &info : diskUseInfos)
    {
        DiskUse diskUse;
        diskUse.setDrivePath(info.driveLetter);
        diskUse.setFileSystem(info.fileSystem);
        diskUse.setDriveType(info.driveType);
        diskUse.setUsageSize(info.usageSize);
        diskAllUsageSize += info.usageSize;
        diskUse.setTotalsize(info.totalSize);
        diskAllTotalSize += info.totalSize;
        diskUseList.append(diskUse);
    }
    diskUseListMutex.unlock();

    diskUseAllMutex.lock();
    diskUseAll.setUsageSize(diskAllUsageSize);
    diskUseAll.setTotalsize(diskAllTotalSize);
    diskUseAllMutex.unlock();

    // 获取网络使用情况
    auto trafficData = networkTrafficMonitor.getInterfaceTraffics();
    networkUseListMutex.lock();
    networkUseList.clear();

    for (const auto &traffic : trafficData)
    {
        NetworkUse networkUse;

        networkUse.setName(traffic.name);                   // 接口名称
        networkUse.setDescription(traffic.description);     // 接口描述
        networkUse.setMacAddress(traffic.macAddress);       // MAC 地址
        networkUse.setBytesReceived(traffic.bytesReceived); // 接收字节数
        networkUse.setBytesSent(traffic.bytesSent);         // 发送字节数
        networkUse.setDownloadRate(traffic.downloadRate);   // 下载速率
        networkUse.setUploadRate(traffic.uploadRate);       // 上传速率

        // 将 qint64 时间戳（毫秒）转为 QDateTime
        networkUse.setTimestamp(QDateTime::fromMSecsSinceEpoch(traffic.lastUpdateTime));

        networkUseList.append(networkUse);
    }
    networkUseListMutex.unlock();
}

DiskUse ServerMonitorCenter::getDiskUseAll()
{
    QMutexLocker locker(&diskUseAllMutex);
    return diskUseAll;
}

void ServerMonitorCenter::run()
{
    QTimer timer;
    connect(&timer, &QTimer::timeout, this, &ServerMonitorCenter::slot_updateInfo);
    timer.start(1000);
    exec();
    timer.stop();
}
